namespace :stat do
  task adjust: :environment do
    ChannelPromotion.all.each {|cp|
      p cp.id
      members = Appointment.joins(:order).where(
          orders: {status: :paid, source: '渠道'},
          timetable_id: cp.promotion_id,
      ).pluck(:member_id, :quantity)
      appointed = []
      members.each {|am| (1..am[1]).each {|i| appointed << am[0]}}
      cp.update_columns(appointed_member: appointed)
    }
  end
  task adjust: :environment do
    Timetable.where("member_price > 0").where(class_start_time: Date.parse("2018-06-01")..Date.parse("2018-07-01")).each {|t|
      p t.id
      members = Appointment.joins(:order).where(
          orders: {status: :paid, source: ["应用", "微信"]},
          timetable_id: t.id,
      ).pluck(:member_id, :quantity)
      appointed = []
      members.each {|am| (1..am[1]).each {|i| appointed << am[0]}}
      t.update_columns(appointed_member: appointed)
    }
  end
  task rebuy: :environment do
    ids = [881, 892]
    report_date = Date.parse("2017-11-01")
    CSV.open('威尔仕.csv', 'wb') do |csv|
      csv << %w"月份 单数 人数 次月复购"
      (0..11).each {

        report_date = report_date + 1.months
        purchaser = Order.joins(:appointment).where(
            store_id: ids,
            status: [:paid, :refunded],
            appointments: {class_start_time: report_date..(report_date + 1.months)}
        ).where("total > 0").pluck(:member_id)

        next_month = report_date + 1.month
        re_purchaser = Order.joins(:appointment, :store).where(
            store_id: ids,
            status: [:paid, :refunded],
            member_id: purchaser.uniq,
            appointments: {class_start_time: next_month..(next_month + 1.months)}
        ).where("total > 0").pluck(:member_id).uniq.size
        p "#{report_date}::#{purchaser.size}::#{re_purchaser}"
        csv << [report_date, purchaser.size, purchaser.uniq.size, re_purchaser]
      }
    end
  end
end
